package com.nowcoder.community.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @ClassName ServiceLogAspect
 * @Description
 * @Author hhwu
 * @Date 2022/5/24 22:41
 * Version 1.0
 **/
@Component
@Aspect
public class ServiceLogAspect {
    /**
     * @Author hhwu
     * @Description //TODO AOP统一记录访问service包下时的日志
     * @Date 9:42 2022/5/25
     **/

    private static final Logger logger = LoggerFactory.getLogger(ServiceLogAspect.class);

    // 指定切入点的返回值为表示任何返回值类型*，切入点为service包下的所有类*的所有方法*的所有参数..
    @Pointcut("execution(* com.nowcoder.community.service.*.*(..))")
    public void pointcut() {
    }

    @Before("pointcut()")// 在指定的切入点前执行
    public void before(JoinPoint joinPoint) {
        /**
         * @Author hhwu
         * @Description //TODO AOP统一记录日志
         * @Date 22:49 2022/5/24
         * @Param [joinPoint]
         * @return void
         **/
        // 用户[1.2.3.4],在[xxx],访问了[com.nowcoder.community.service.xxx()].
        // 获取用户id
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes == null) return;// 如果service不是通过controller调用的，就不会有request请求 ，attributes就为空，例如EvenConsumer中调用service
        HttpServletRequest request = attributes.getRequest();
        String ip = request.getRemoteHost();

        // 获取访问时间
        String now = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());

        // 获取访问的类和方法
        String target = joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName();
        
        logger.info(String.format("用户[%s],在[%s],访问了[%s].", ip, now, target));
    }
}
